package com.zealcomm.ivcscustomer.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.zco.util.LogUtil
import com.zco.util.ToastUtil
import com.zealcomm.commonui.base.BaseFragment
import com.zealcomm.ivcscustomer.R
import com.zealcomm.ivcscustomer.databinding.FragmentScanBinding
import com.zealcomm.ivcscustomer.service.MainActivity

class ScanFragment : BaseFragment(), QRCodeView.Delegate {

    private lateinit var binding: FragmentScanBinding
    private val handler = Handler()
    private var scanResult = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentScanBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.zxingview.setDelegate(this)
        handler.postDelayed({
            binding.zxingview.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
            binding.zxingview.startSpotAndShowRect() // 显示扫描框，并开始识别
        }, 100)

        binding.ivClose.setOnClickListener {
            ToastUtil.showTopToast("您已取消扫码")
            (activity as MainActivity).removeFragment()
        }
    }

    override fun onStop() {
        binding.zxingview.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        super.onStop()
    }

    override fun onDestroy() {
        binding.zxingview.onDestroy() // 销毁二维码扫描控件
        binding == null
        if (!scanResult && activity is MainActivity) {
            (activity as MainActivity).onScanCodeCanceled()
        }
        super.onDestroy()
    }

    override fun onScanQRCodeSuccess(result: String?) {
        scanResult = true
        LogUtil.d("扫码结果：$result , format: ${binding.zxingview.format}")
        ToastUtil.showTopToast("扫码成功")
        vibrate()
        binding.zxingview.stopCamera()
        if (activity is MainActivity) {
            (activity as MainActivity).onScanQRCodeSuccess(result, binding.zxingview.barcodeFormat)
        }
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        var tipText: String = binding.zxingview.scanBoxView.tipText
        val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                binding.zxingview.scanBoxView.tipText = tipText + ambientBrightnessTip
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
                binding.zxingview.scanBoxView.tipText = tipText
            }
        }
    }

    override fun onScanQRCodeOpenCameraError() {
        ToastUtil.showShort("打开相机出错")
    }

    private fun vibrate() {
        (context?.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator)?.vibrate(200)
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {}

    override
    val layoutId: Int
        get() = R.layout.fragment_scan

}